package com.nf.health.app.activity.my;

import android.database.ContentObserver;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.miansearch.impl.OnChecktemLinstener;
import com.nf.health.app.activity.my.adapter.SearchDrugStoreAdapter;
import com.nf.health.app.activity.my.bean.DrugStoreBean;
import com.nf.health.app.activity.my.medicine.MyMedicineDetailActivty;
import com.nf.health.app.core.MyGsonBuilder;
import com.nf.health.app.customview.AddressPopupWindow;
import com.nf.health.app.customview.DividerListItemDecoration;
import com.nf.health.app.http.Act;
import com.nf.health.app.service.ServiceData;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.LocationUtil;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * 药店
 * @author changpeng
 */
public class SearchDrugStoreActivity extends BaseActivity {

    @Bind(R.id.recyclerview)
    RecyclerView mRecyclerView;
    @Bind(R.id.tv_back)
    TextView mTvBack;
    @Bind(R.id.tv_open_gps)
    TextView mTvOpenGps;
    @Bind(R.id.tv_address)
    TextView mTvAddress;
    @Bind(R.id.tv_title)
    TextView mTvTitle;
    @Bind(R.id.et_main_search)
    EditText mEtMainSearch;
    @Bind(R.id.ll_search)
    LinearLayout mLlSearch;
    @Bind(R.id.rl_search)
    RelativeLayout mRlSearch;
    @Bind(R.id.rl_location_tip)
    RelativeLayout mRlLocationTip;
    @Bind(R.id.tv_no_data)
    TextView mTvNoData;

    private AddressPopupWindow mPopupWindow;
    LinkedHashMap<String, LinkedList<String>> listArea = null;
    private boolean isOpenLoadtion = false;//是不是开启定位
    private String locationAddress = "";
    private String mCity = "", mHname = "", mProvince = "";
    private SearchDrugStoreAdapter mAdapter;
    private List<DrugStoreBean.ListBean> mListBeen = new ArrayList<>();
    private static final String NATIONAL = "全国";
    private static final String ALL_CITY = "全部";
    private boolean mGoOpenGps = false;
    private LocationManager mLocationManager;

    private boolean isLocation;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.title_drug_store);
        setContent(R.layout.activity_search_drug_store);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();

    }

    private void initData() {
        listArea = ServiceData.getMyCityArea2(this);
    }

    private void initView() {
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        mAdapter = new SearchDrugStoreAdapter(this, mListBeen);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerListItemDecoration(this, LinearLayoutManager.VERTICAL));
        mRecyclerView.setAdapter(mAdapter);
        showSelectAddressTitle();
        //显示开启定位  前提要开启定位权限
        if(!LocationUtil.gpsIsOpen(SearchDrugStoreActivity.this)){
            mRlLocationTip.setVisibility(View.VISIBLE);
        }else{
            mRlLocationTip.setVisibility(View.GONE);
        }

        mTvAddress.setText(NATIONAL);
        provider.dHospitalList("", "", "");

        String brand = android.os.Build.BRAND;
        if("Xiaomi".equals(brand)){
            if(!LocationUtil.isOpenGPS(SearchDrugStoreActivity.this)){
                mRlLocationTip.setVisibility(View.VISIBLE);
            }
        }

    }

    private void initListener() {
        mTvAddress.setOnClickListener(this);
        mTvOpenGps.setOnClickListener(this);
        mEtMainSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mHname = s.toString();
                provider.dHospitalList(mCity, s.toString(), mProvince);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mAdapter.setOnItemClickListener(new SearchDrugStoreAdapter.OnItemClickListener() {
            @Override
            public void onClickListener(View itemView, int position) {
                mGoOpenGps = false;
                Bundle bundle = new Bundle();
                bundle.putSerializable(MyMedicineDetailActivty.MODEL_MYMEDICINEDETAILACTIVTY, mListBeen.get(position));
                ActivityUtils.showActivity(SearchDrugStoreActivity.this,MyMedicineDetailActivty.class,bundle);

            }
        });
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if (Act.Flag.FLAG_D_HOSPITAL_LIST.equals(actionName)) {
            Gson gson = new MyGsonBuilder().createGson();
            DrugStoreBean bean = gson.fromJson(object + "", DrugStoreBean.class);
            List<DrugStoreBean.ListBean> newList = bean.getList();
            mListBeen.clear();
            mListBeen.addAll(newList);
            mAdapter.notifyDataSetChanged();
            if(mListBeen == null || mListBeen.size() == 0){
                mTvNoData.setVisibility(View.VISIBLE);
            }else{
                mTvNoData.setVisibility(View.GONE);
            }
            if(!isLocation) {
                initMyLocation();
            }
            isLocation = true;
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
    }

    @Override
    protected void onStart() {
        super.onStart();
        getContentResolver()
                .registerContentObserver(
                        Settings.Secure
                                .getUriFor(Settings.System.LOCATION_PROVIDERS_ALLOWED),
                        false, mGpsMonitor);
    }



    @Override
    protected void onRestart() {
        super.onRestart();
        if(!LocationUtil.gpsIsOpen(this)){
            //如果没开启定位
            mRlLocationTip.setVisibility(View.VISIBLE);
            //mTvAddress.setText(NATIONAL);
            //provider.dHospitalList("", "", "");
        }else{
            mRlLocationTip.setVisibility(View.GONE);
            initMyLocation();
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_address:
                showLocationList();
                break;
            case R.id.tv_open_gps:
                LocationUtil.setGoGPSMain(SearchDrugStoreActivity.this);
                mGoOpenGps = true;
                break;
        }
    }

    private void showSelectAddressTitle() {
        mLlSearch.setVisibility(View.VISIBLE);
        mTvAddress.setVisibility(View.VISIBLE);
        mTvBack.setVisibility(View.GONE);
        mTvTitle.setVisibility(View.GONE);
    }

    private void showSearchStoreTitle() {
        mTvBack.setVisibility(View.VISIBLE);
        mTvTitle.setVisibility(View.VISIBLE);
        mLlSearch.setVisibility(View.GONE);
        mTvAddress.setVisibility(View.GONE);
    }

    private void showLocationList() {
        if (mPopupWindow == null) {
            mPopupWindow = new AddressPopupWindow(SearchDrugStoreActivity.this)
                    .regisitMyMenuOnClickListaner(new OnChecktemLinstener() {
                        @Override
                        public void onClickFirstMenu(String mainResult) {
                            mTvAddress.setText(mainResult);
                            if(NATIONAL.equals(mainResult)){
                                mTvAddress.setText(NATIONAL);
                                mCity = "";
                                mHname = "";
                                mProvince = "";
                                provider.dHospitalList(mCity, mHname, mProvince);
                            }
                        }

                        @Override
                        public void onClickSecondMenu(String subResult) {
                            if(ALL_CITY.equals(subResult.split("\\|")[1])){
                                mTvAddress.setText(subResult.split("\\|")[0]);
                                mProvince = subResult.split("\\|")[0];
                                mCity = "";
                                provider.dHospitalList(mCity, mHname, mProvince);
                            }else{
                                mTvAddress.setText(subResult.split("\\|")[1]);
                                mCity = subResult.split("\\|")[1];
                                mProvince = subResult.split("\\|")[0];
                                provider.dHospitalList(mCity, mHname, mProvince);
                            }

                        }
                    });
            mPopupWindow.setOnDismissListener(new AddressPopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    showSelectAddressTitle();
                }
            });
            mPopupWindow.setMyListData2(listArea, locationAddress, isOpenLoadtion);
        } else {
            mPopupWindow.refreshMylocationData(locationAddress, isOpenLoadtion);
        }
        if (!mPopupWindow.isShowing()) {
            mPopupWindow.showAsDropDown(mRlSearch);
            showSearchStoreTitle();
        }
    }

    /**
     * 定位相关
     */
    public void  initMyLocation() {

        LocationUtil.initial(this, new LocationUtil.CallAddressBack() {
            @Override
            public void complete(double latitude, double longitude, String address) {
                LogUtil.e("SearchDrugStoreActivity", "经：" + latitude + " wei: " + " longitude " + longitude + " 地址： " + address);
                String longitudeStr = String.valueOf(longitude);
                String latitudeStr = String.valueOf(latitude);
                isOpenLoadtion = true;
                String getMyLocationAddress = ServiceData.getCityDefaultPosition2(listArea, address);
                try {
//                    if (!TextUtils.isEmpty(getMyLocationAddress)) {
//                        //网络定位成功也走这里，为了和IOS保持一致，只允许GPS定位
//                        if(!LocationUtil.isOpenGPS(SearchDrugStoreActivity.this)){
//                            mRlLocationTip.setVisibility(View.VISIBLE);
//                            mTvAddress.setText(NATIONAL);
//                            mCity = "";
//                            mHname = "";
//                            mProvince = "";
//                            provider.dHospitalList(mCity, mHname, mProvince);
//                        }else{
//                            mRlLocationTip.setVisibility(View.GONE);
                            String cityArray[] = getMyLocationAddress.split("\\|");
                            mTvAddress.setText(cityArray[1]);
                            address = getMyLocationAddress;
                            mCity = cityArray[1];
                    //省
                    String provinceS = PreferenceHelper.getProvince();
                    //市
                    String cityS = PreferenceHelper.getCity();
                    //区
                    String districtS = PreferenceHelper.getDistrict();
                    //直辖市 只有两级
                    if(provinceS.equals(cityS)){
                        mProvince = cityS;
                        mCity = districtS;
                    }else{
                        mProvince = provinceS;
                        mCity = cityS;
                    }
                    provider.dHospitalList(mCity, mHname, mProvince);
                    locationAddress = address;

//                        }
//
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void callRemainQuestFaild() {
                //获取地址失败
                isOpenLoadtion = false;
                mTvAddress.setText(NATIONAL);
                mCity = "";
                mHname = "";
                mProvince = "";
                provider.dHospitalList(mCity, mHname, mProvince);
            }
        });
    }

    Handler mHandler = new Handler();

    private final ContentObserver mGpsMonitor = new ContentObserver(null) {
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            //GPS 状态改变时回调
            boolean enabled = mLocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            System.out.println("gps enabled? " + enabled);
            if(enabled){
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initMyLocation();
                    }
                },200);
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }
}
